<?php

$accessGroups = $DB->fetchAll('SELECT * FROM '.cms_db_prefix().'iusers_groups');
$countries = $DB->fetchAll("SELECT * FROM ".cms_db_prefix().'iusers_countries ORDER BY title ASC');
$defAccessGroups = $this->GetConfig('default_groups_for_admin_registration');




if(Antz_IntelliForm::submitted('new')){

    // process to create a new user
    $username = post('username');
    $busName = post('business_name');
    $email = post('email');
    $emailMD5 = md5(strtolower($email));
    $password = post('password');
    $fName = post('first_name');
    $lName = post('last_name');
    $groups = explode(',', post('access_groups'));
    $country = preg_replace('/[^a-zA-Z0-9]/', '', post('country', 'NZ'));
    $city = (int) post('new_city', 0);

    $error = false;

    if(trim($username) == ''){
        $error = true;
        Antz::addFormError('username', $this->Lang('cannot_be_blank'));
    }else{
        $safeUsername = preg_replace('/[^a-zA-Z0-9\-_]/', '', $username);
        if($safeUsername == '' || $safeUsername != $username){
            $error = true;
            Antz::addFormError('username', $this->Lang('invalid_chars'));
        }else{
            $lowerUsername = strtolower($safeUsername);
            if($DB->countRows(cms_db_prefix().'iusers', "LOWER(username) = '{$safeUsername}'")>0){
                $error = true;
                Antz::addFormError('username', $this->Lang('already_registered'));
            };
            if(in_array(strtolower($username), $DISALLOWED_USERNAMES)){
                $error = true;
                Antz::addFormError('username', $this->Lang('disallowed_username'));
            };

        };


    };

    // password
    if(strlen($password) < 6 || strlen($password) > 20){
        $error = true;
        Antz::addFormError('password', $this->Lang('6-20_chars'));
    };
    // email
    if(trim($email)==''){
        $error = true;
        Antz::addFormError('email', 'Cannot be blank');
    }else{
        if(!Antz_Filter::checkEmail($email)){
            $error = true;
            Antz::addFormError('email', $this->Lang('invalid_chars'));
        }else{
            if($DB->countRows(cms_db_prefix().'iusers', "email_md5 = '{$emailMD5}'")>0){
                $error = true;
                Antz::addFormError('email', $this->Lang('already_registered'));
            };
        };
    };
    // Name
    $fName = substr($fName, 0, 24);
    $lName = substr($lName, 0, 24);
    if($insistFirstName && $fName == ''){
        $error = true;
        Antz::addFormError('first_name');
    }else{
        if(strlen($fName)>12){
            $error = true;
            Antz::addFormError('first_name', $this->Lang('max_12_chars'));
        };
    };
    if($insistLastName && $lName == ''){
        $error = true;
        Antz::addFormError('last_name');
    }else{
        if(strlen($lName)>12){
            $error = true;
            Antz::addFormError('last_name', $this->Lang('max_12_chars'));
        };
    };
    // country and city
    if($this->GetConfig('be_country_required') == 1 && ($country == 0 || $DB->countRows(cms_db_prefix().'iusers_countries', "id = '{$country}'")==0)){
        $error = true;
        Antz::addFormError('country');
    };
    if($this->GetConfig('be_city_required') == 1 && ($city == 0 || $DB->countRows(cms_db_prefix().'iusers_cities', "id = '{$city}'")==0)){
        $error = true;
        Antz::addFormError('city');
    };
    
    foreach($groups as $k=>$groupKey){
        if($DB->countRows(cms_db_prefix().'iusers_groups', "keyname = '{$groupKey}'")==0){
            unset($groups[$k]);
        };
    };
    if(count($groups)==0){
        $error = true;
        Antz::addFormError('accessGroups');
    };

	// hookup to other modules
	$hookParams = array(
		'error' => false,
		'errors' => array()
	);
	$newParams = Antz::Hookup('IUsers_AdminNewCheck', $hookParams);
	$hookParams = $newParams['params'];
	unset($newParams);
	if($hookParams['error']){
		$error = true;
		if(count($hookParams['errors'])>0){
			foreach($hookParams['errors'] as $errorMsg){
				Antz::addError($errorMsg);
			};
		};
	};


    if(!$error){
        // safe to process
        $dbParams = array(
            'username' => $username,
            'business_name' => $busName,
            'email_crypt' => $CRYPT->crypt($email),
            'email_md5' => $emailMD5,
            'pass' => $CRYPT->crypt($password),
            'first_name' => $fName,
            'last_name' => $lName,
            'country' => $country,
            'city' => $city,
            'register_tstamp' => time(),
            'email_subscriber' => $this->GetConfig('auto_subscribe_new_users')
        );

        if($this->GetConfig('admin_email_verification')==1){
            // email verification is required
            $dbParams['new_email'] = strtolower($email);
            $hash = md5($email.rand(0, 99));
            $dbParams['new_email_hash'] = $hash;
            $dbParams['status'] = 2;
            $emailVerification = true;
        }else{
            // user is fully registered and ready to go
            $dbParams['status'] = 1;
            $emailVerification = false;
            $hash = '';
        };

        // insert the user into the database
        $userid = $DB->insert(cms_db_prefix().'iusers', $dbParams);
        $uData = $dbParams;

        // register their belonging to the groups
        foreach($groups as $k=>$v){
            $v = preg_replace('/[^a-zA-Z0-9_\-]/', '', $v);
            if($DB->countRows(cms_db_prefix().'iusers_groups', "keyname = '{$v}'")==0) continue;
            $DB->insert(cms_db_prefix().'iusers_to_groups', array('group_key'=>$v, 'user_id'=>$userid));
        };

        // send the welcome message
        $loginId = $this->GetConfig('login_id');

        if($this->GetConfig('secure_login')==1){
            $loginUrl = str_replace('http://', 'https://', $Antz->getUrlById($loginId));
        }else{
            $loginUrl = $Antz->getUrlById($loginId);
        };

        $sitename = $DB->oneValue(cms_db_prefix().'siteprefs', 'sitepref_value', "sitepref_name = 'sitename'");
        $subject = 'Welcome to '.$sitename;
        if($emailVerification) $tpl = 'admin.register.verify.php';
        else $tpl = 'admin.register.noverify.php';
        $emailParams = array(
            'login_url' => $loginUrl,
            'name' => $fName.' '.$lName,
            'email' => $email,
            'username' => $username,
            'password' => $password,
            'sitename' => $sitename,
            'email_verification_url' => $Antz->addParamsToUrl($Antz->getUrlById($this->GetConfig('email_verification_id')), array('email'=>$email, 'hash'=>$hash)),
            'email_verification_url_htmlentities' => $Antz->addParamsToUrl($Antz->getUrlById($this->GetConfig('email_verification_id')), array('email'=>$email, 'hash'=>$hash), true),
        );
        $msg = $this->ProcessEmailTemplate($tpl, $emailParams);
        $toFrom = array(
            'toName' => $fName.' '.$lName,
            'toEmail' => $email
        );
        Antz_Email::sendRaw($subject, $msg, $toFrom, true);

        // report success
        Antz::addSuccess($this->Lang('success_new_member'));

        // hookup to other modules
        $uData['email'] = $email;
        $uData['password'] = $password;
        $uData['id'] = $userid;
		$hookParams = array('user_data' => $uData);
		$newParams = Antz::Hookup('IUsers_AdminNewProcess', $hookParams);
		$hookParams = $newParams['params'];
		unset($newParams);
		
		Antz::redir($actionUrls['new']);

    }else{
        // there was a form error
        Antz::addError($this->Lang('fields_are_empty'));

    }

}

$accessGroups = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}iusers_groups ORDER BY title ASC");

// make our group selector
$groupOptions = array('0'=>$this->Lang('add_remove'));
foreach($accessGroups as $k=>$v){
	$groupOptions[$v['keyname']] = $v['title'].' ['.$v['keyname'].']';
}

$groupFields = array(
	'type' => 'select',
	'name' => 'groupSel',
	'value' => $this->Lang('add_remove'),
	'label' => '',
	'options' => $groupOptions,
	'extra' => array(
		array(
			'command' => 'addJsEvent',
			'params' => array(
				"'onchange'",
				"'IUsers_Admin.new_addGroup(\'accessGroups\', this)'"
			)
		)
	)
);

$groupSel = Antz::makeFormComponent($groupFields, false, false);

$countries = $DB->fetchAll("SELECT * FROM ".cms_db_prefix().'iusers_countries ORDER BY title ASC');
if(post('country')=='') $country = $this->GetConfig('default_country');
else $country = post('country');
$minPopulation = $this->GetConfig('cities_min_population');
$cities = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}iusers_cities WHERE country_id = '{$country}' AND population >= {$minPopulation} ORDER BY title ASC");

$countryOptions = array();
foreach($countries as $k=>$v){
	$countryOptions[$v['id']] = $v['title'];
}
$cityOptions = array();
foreach($cities as $k=>$v){
	$cityOptions[$v['id']] = $v['title'];
}


// gonna define the form fields as an array because other modules can add their fields to it (See Antz::Hookup())
$formFields = array(
	array(
		'type' => 'hidden',
		'name' => 'action',
		'value' => 'new',
		'label' => ''
	),
	array(
		'name' => 'username',
		'value' => post('username'),
		'type' => 'text',
		'label' => $this->Lang('username'),
		'required' => true
	),
	array(
		'name' => 'email',
		'value' => post('email'),
		'type' => 'text',
		'label' => $this->Lang('email'),
		'required' => true
	),
	array(
		'name' => 'password',
		'value' => post('password'),
		'type' => 'text',
		'label' => $this->Lang('password'),
		'required' => true,
		'extra' => array(
		  array(
        'command' => 'addAttribute',
        'params' => array(
          '"autocomplete"', '"off"'
        )
      )
    )
	),
	array(
		'name' => 'business_name',
		'type' => 'text',
		'value' => post('business_name'),
		'label' => $this->Lang('business_name')
	),
	array(
		'name' => 'first_name',
		'value' => post('first_name'),
		'type' => 'text',
		'label' => $this->Lang('first_name'),
		'required' => (bool) $this->GetConfig('be_insist_fname') 
	),
	array(
		'name' => 'last_name',
		'value' => post('last_name'),
		'type' => 'text',
		'label' => $this->Lang('last_name'),
		'required' => (bool) $this->GetConfig('be_insist_lname') 
	),
	array(
		'name' => 'country',
		'value' => post('country', $this->GetConfig('default_country')),
		'type' => 'select',
		'label' => $this->Lang('country'),
		'options' => $countryOptions,
		'id' => 'countrySel',
		'extra' => array(
				0 => array(
				'command' => 'addJsEvent',
				'params' => array(
					"'onchange'",
					"'IUsers_Places.getCitiesForCountry(\'{$this->config['root_url']}\', this, \'citySel\')'"
				)
			)
		),
		'required' => (bool) $this->GetConfig('fe_country_required') 
	),
	array(
		'name' => 'city',
		'value' => post('city'),
		'type' => 'select',
		'label' => $this->Lang('city'),
		'options' => $cityOptions,
		'id' => 'citySel',
		'required' => (bool) $this->GetConfig('fe_city_required') 
	),
	array(
		'type' => 'textarea',
		'name' => 'access_groups',
		'value' => $this->GetConfig('default_groups_for_admin_registration'),
		'label' => $this->Lang('member_of_groups'),
		'aftertext' => $groupSel->render(),
		'id' => 'accessGroups',
		'class' => 'grayed-out small',
		'extra' => array(
			array(
				'command' => 'addJsEvent',
				'params' => array(
					"'onfocus'",
					"'blur(this)'"
				)
			)
		)
	)
);

// implement the hook to get extra form fields from other modules
$hookParams = array('form_fields' => $formFields);
$newParams = $Antz->Hookup('IUsers_AdminNewForm', $hookParams);
$formFields = $newParams['params']['form_fields'];
unset($newParams);

$formFields = Antz::prepareRapidForm($formFields, $this->Lang('register_legend'));


$form = Antz::makeForm($formFields, 'new');

$form->addSubmit($this->Lang('submit'));

$SMARTY->assign('newForm', $form->render());


echo $this->ProcessTemplate('admin.new.php');
